package com.ch.android.lookforkotlinv2.vm

import android.app.Application
import android.content.ContentResolver
import android.net.Uri
import android.provider.MediaStore
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.ch.android.networklib.RequestClient
import com.ch.android.networklib.data.API_STATUS_OK
import com.ch.android.networklib.data.BaseResultData
import com.ch.android.networklib.data.OpenLiveData
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream


/**
 * Author: conghao
 * Date: 2024/1/27 10:40
 * Description: PreviewModel
 */
class PreviewModel(application: Application) : AndroidViewModel(application) {
    val openLiveData: MutableLiveData<OpenLiveData> = MutableLiveData()
    val error: MutableLiveData<Throwable> = MutableLiveData()
    fun requestOpenLive(cover: Uri, liveTypeId: Int, liveTitle: String, sessionId: String) {
        val file = convert2File(cover)
        if (file != null) {
            val requestBody = file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
            val part = MultipartBody.Part.createFormData("liveCoverImage", file.name, requestBody)
            viewModelScope.launch {
                try {

                    var resultData: BaseResultData<OpenLiveData?> = RequestClient.getApiService(getApplication()).openLive(
                        sessionId = sessionId, liveType = liveTypeId, liveTitle = liveTitle, part = part
                    )
                    if (resultData.status == "1003") { //未关闭上次的直播
                        val resultClose = RequestClient.getApiService(getApplication()).closeLive(sessionId)
                        resultData = RequestClient.getApiService(getApplication()).openLive(
                            sessionId = sessionId, liveType = liveTypeId, liveTitle = liveTitle, part = part
                        )
                    }
                    withContext(Dispatchers.Main) {
                        if (resultData.status == API_STATUS_OK) {
                            openLiveData.value = resultData.result!!
                        } else {
                            error.value = Throwable(resultData.message)
                        }
                    }
                } catch (e: Exception) {
                    withContext(Dispatchers.Main) {
                        error.value = e
                    }
                }

            }

        }
    }

    private fun convert2File(uri: Uri): File? {
        // 获取ContentResolver实例
        val resolver: ContentResolver = getApplication<Application>().contentResolver
        // 或者将图片内容保存到本地文件
        try {
            val inputStream = resolver.openInputStream(uri)
            if (inputStream != null) {
                val destinationFile: File = File(getApplication<Application>().cacheDir, "live_cover.jpg") // 选择一个合适的存储路径
                val out: OutputStream = FileOutputStream(destinationFile)
                val buffer = ByteArray(4 * 1024) // Or other buffer size
                var read: Int
                while (inputStream.read(buffer).also { read = it } != -1) {
                    out.write(buffer, 0, read)
                }
                out.flush()
                out.close()
                inputStream.close()
                return destinationFile
            }
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return null
    }
}